<template>
  <a-flex horizontal gap="small"  justify="center" style="margin-top: 10px; margin-right: 60px">
    <div style="width: 20%; padding: 2px; overflow: auto; height: 600px">
      <!-- 可聊天对象列表 -->
      <a-skeleton avatar :paragraph="{ rows: 3 }" active v-if="chatTargetListLoading"/>
      <a-result title="暂时还没有消息哦！" v-if="chatTargetList.length === 0 && !chatTargetListLoading">
        <template #icon>
          <MessageFilled style="color: #aaaaaa"/>
        </template>
      </a-result>
      <div v-for="(target, index) in chatTargetList"
           :style="{margin: '2px', padding: '6px', backgroundColor: currentChatTargetIndex === index ? '#dcdbdb' : '', cursor: 'pointer'}"
           @click="handleClickChatTarget(index)"
      >
        <a-row justify="space-around" align="middle">
          <a-col :span="6">
            <a-badge :count="target.unReadNum">
              <a-avatar :src="target.userInfo.header" :size="50"/>
            </a-badge>
          </a-col>
          <a-col :span="18">
            <a-space style="margin-left: 6px" direction="vertical">
              <a-space align="center" >
                <a-typography-text strong>{{ target.userInfo.nickname }}</a-typography-text>
                <a-typography-text type="secondary" v-if="target.sendTime !== null">{{formatISODate(target.sendTime)}}</a-typography-text>
              </a-space>
              <div style="text-overflow: ellipsis;
                          overflow: hidden;
                          display: -webkit-box;
                          -webkit-line-clamp: 1;
                          -webkit-box-orient: vertical;">
                <a-typography-text type="secondary" v-if="target.lastMsg !== null">{{target.lastMsg}}</a-typography-text>
              </div>
            </a-space>
          </a-col>
        </a-row>
      </div>
    </div>
    <div id="chat-window" style="width: 80%; padding: 4px; background-color: #f2f3f5;text-align: center;">
      <!-- 聊天窗 -->
      <a-space direction="vertical" v-if="chatTargetList.length > 0" :size="1" style="width: 100%">
        <div>
          <a-divider>
            <a-typography-title :level="5">{{chatTargetList[currentChatTargetIndex].userInfo.nickname}}</a-typography-title>
          </a-divider>
        </div>
        <div id="chat-pop-box" ref="chatPopBox" @scroll="handleChatPopBoxScroll" style="height: 400px;overflow: auto;">
          <!-- 聊天气泡列表 -->
          <div v-for="(chatItem, index) in chatPopList">
            <div style="text-align: right;padding: 2px;margin: 2px" v-if="chatItem.fromId === userSession.userId">
              <!-- 自己的聊天气泡 -->
                <a-space direction="horizontal" :size="1">
                  <a-typography-text type="secondary" >{{formatISODate(chatItem.sendTime)}}</a-typography-text>
                  <div class="chat-bubble">
                    {{ chatItem.msgContent }}
                  </div>
                 <a-avatar :src="userSession.header" :size="40"/>
              </a-space>
            </div>
            <div style="text-align: left;padding: 2px;margin: 2px" v-else>
              <!-- 别人的聊天气泡 -->
              <a-space direction="horizontal" :size="1">
                <a-avatar :src="chatTargetList[currentChatTargetIndex].userInfo.header" :size="40"/>
                <div class="chat-other-bubble">
                  {{ chatItem.msgContent }}
                </div>
                <a-typography-text type="secondary" >{{formatISODate(chatItem.sendTime)}}</a-typography-text>
              </a-space>
            </div>
          </div>
        </div>
        <div id="chat-input">
          <a-divider />
          <a-row justify="space-around" align="middle">
            <a-col :span="20">
              <!-- 输入框 -->
              <a-textarea v-model:value="msgContent"
                          :auto-size="{ minRows: 3, maxRows: 5 }"
                          showCount allowClear :maxlength="maxMsgContentLength"/>
            </a-col>
            <a-col :span="4">
              <a-button type="primary" @click="sendMsg">发送</a-button>
            </a-col>
          </a-row>
        </div>
      </a-space>
    </div>
  </a-flex>
</template>

<script setup>
import {ref, onBeforeMount, watch, onMounted, nextTick, onBeforeUnmount, h} from "vue";
import {MessageFilled} from "@ant-design/icons-vue";
import {formatISODate} from "@/utils/timeUtil.js";
import Pubsub from "pubsub-js";
import {getChatTargetList, getChatTargetInfo, getChatHistories} from "@/api/MessageRequest.js";
import {message, notification} from "ant-design-vue";
import router from "@/router/index.js";
import {useSocketStore} from "@/utils/websocket.js";

const props = defineProps({
  userSession: {
    type: Object,
    required: true,
    default: null
  },
});

const wsStore = useSocketStore();

const userSessionKey = Pubsub.subscribe("user-session", (msg, data) => {
  if(data !== null && data !== undefined)
    userSession.value = data;
});

const userSession = ref({});
const msgContent = ref('');
const maxMsgContentLength = 500;

const chatTargetListLoading = ref(true);    // 聊天对象列表加载标识
const chatTargetList = ref([]);             // 聊天对象列表

const currentChatTargetIndex = ref(-1);     // 当前聊天对象索引
const chatPopListLoading = ref(false);     // 聊天内容列表加载标识
const chatPopList = ref([]);               // 聊天内容气泡列表
let chatPopListPageIndex = 1;        // 聊天气泡列表分页索引
const pageSize = 10;

// 监听当前聊天对象索引
watch(currentChatTargetIndex, (val) => {
  chatPopListPageIndex = 1;

  // 获取聊天记录
  getChatHistories(chatTargetList.value[val].userInfo.userId, chatPopListPageIndex, pageSize).then(res => {
    console.log('获取的聊天记录', res.data);
    if(res.code === 0) {
      chatPopList.value = res.data.chatMsgList;
      toChatPopListEnd();
      if(chatTargetList.value[val].unReadNum > 0) {
        setTimeout(() => {
          if (chatTargetList.value[val].unReadNum >= res.data.chatMsgList.length) {
            chatTargetList.value[val].unReadNum -= res.data.chatMsgList.length;
          } else {
            chatTargetList.value[val].unReadNum = 0;
          }

        }, 2000);
      }
    } else {
      message.warn(res.msg);
    }
  })
});

// 监听聊天气泡列表
// watch(chatPopList, (val) => {
//   toChatPopListEnd();
// },{
//   deep: true, // 深度监听
//   flush: 'post'
// });

watch(() => wsStore.msg, (msg) => {
  console.log('ws消息', msg);
  if(msg.type === 2) {
    // 私聊消息
    if(msg.fromId === chatTargetList.value[currentChatTargetIndex.value].userInfo.userId) {
      // 发送对象为当前聊天窗对象
      addChatPop(msg.fromId, msg.msgContent, 1, msg.contentFormat, msg.sendTime);
      chatTargetList.value[currentChatTargetIndex.value].sendTime = msg.sendTime;
      chatTargetList.value[currentChatTargetIndex.value].type = msg.type;
      chatTargetList.value[currentChatTargetIndex.value].lastMsg = msg.content;

      toChatPopListEnd();
    } else {
      let flag = false;
      for (let i = 0; i < chatTargetList.value.length; i++) {
        if(msg.fromId === chatTargetList.value[i].userInfo.userId) {
          // 发送对象为聊天对象列表中除去聊天窗对象的对象
          flag = true;
          chatTargetList.value[i].unReadNum += 1;
          chatTargetList.value[i].sendTime = msg.sendTime;
          chatTargetList.value[i].type = msg.type;
          chatTargetList.value[i].lastMsg = msg.content;

          const item = chatTargetList.value.splice(i,1)[0];
          chatTargetList.value.unshift(item);
          break;
        }
      }

      if(!flag) {
        // 发送对象为聊天对象列表外的用户
        getChatTargetInfo(msg.fromId).then(res => {
          if(res.code === 0) {
            chatTargetList.value.unshift(res.data);
          } else {
            message.warn(res.msg);
          }
        })
      }
    }
  }
});

/**
 * 跳转到聊天气泡列表的末尾
 */
function toChatPopListEnd() {
  const chatPopBox = document.getElementById('chat-pop-box');
  if(typeof chatPopBox !== 'undefined' && chatPopBox !== null){
    nextTick(()=>{
      chatPopBox.scrollTo(0, chatPopBox.scrollHeight - chatPopBox.clientHeight)
    })
  }
}

/**
 * 点击聊天对象处理方法
 * @param index
 */
function handleClickChatTarget(index) {
  currentChatTargetIndex.value = index;
  chatTargetList.value[index].unReadNum = 0;
}

/**
 * 聊天气泡窗滚动处理
 * @param e
 */
function handleChatPopBoxScroll (e) {
  const clientHeight = e.target.clientHeight;
  const scrollHeight = e.target.scrollHeight;
  const scrollTop = e.target.scrollTop;

  //console.log(`clientHeight: ${clientHeight}, scrollHeight: ${scrollHeight}, scrollTop: ${scrollTop}, `);

  if (scrollTop === 0) {
    if(!chatPopListLoading.value) {
      chatPopListLoading.value = true;
      chatPopListPageIndex += 1;
      getChatHistories(chatTargetList.value[currentChatTargetIndex.value].userInfo.userId, chatPopListPageIndex, pageSize).then(res => {
        chatPopListLoading.value = false;
        console.log('刷新的聊天记录', res.data);
        if(res.code === 0) {
          for (let i = res.data.chatMsgList.length - 1; i >=0 ; i--) {
            chatPopList.value.unshift(res.data.chatMsgList[i]);
          }
          if(chatTargetList.value[currentChatTargetIndex.value].unReadNum > 0) {
            setTimeout(() => {
              if (chatTargetList.value[currentChatTargetIndex.value].unReadNum >= res.data.chatMsgList.length) {
                chatTargetList.value[currentChatTargetIndex.value].unReadNum -= res.data.chatMsgList.length;
              } else {
                chatTargetList.value[currentChatTargetIndex.value].unReadNum = 0;
              }
            }, 2000);
          }

        }
      });
    }
  }
}

function sendMsg() {
  if(msgContent.value !== '' && msgContent.value.length <= maxMsgContentLength){
    console.log('发送消息...', msgContent.value);
    wsStore.sendMsgParam.toId = chatTargetList.value[currentChatTargetIndex.value].userInfo.userId;
    wsStore.sendMsgParam.msgContent = msgContent.value;
    wsStore.sendMsgParam.type = 2;
    wsStore.sendMsgParam.status = 0;
    wsStore.sendMsgParam.code = 0;
    wsStore.sendMsgParam.contentFormat = 0;
    wsStore.sendTextMsg();
    addChatPop(userSession.value.userId, msgContent.value, 1, 0);
    toChatPopListEnd();
    msgContent.value = '';
  }
}

function addChatPop(fromId, msgContent, status, contentFormat, sendTime = new Date()){
  chatPopList.value.push({fromId, msgContent, status, contentFormat, sendTime});
}

onBeforeMount(() => {
  // 获取可聊天对象列表
  chatTargetListLoading.value = true;
  getChatTargetList().then((res) => {
    chatTargetListLoading.value = false;
    if (res && res.code === 0) {
      chatTargetList.value = res.data;
      const urlTarget = router.currentRoute.value.query.targetId; // rul携带聊天对象的userId
      if(typeof urlTarget !== 'undefined') {
        // 当前url携带聊天对象ID
        let flag = false; // urlTarget 不在列表中的标志
        for(let i = 0; i < chatTargetList.value.length; i++) {
          if(chatTargetList.value[i].userInfo.userId === urlTarget) {
            currentChatTargetIndex.value = i;
            let temp = {...chatTargetList.value[i]};
            chatTargetList.value.splice(i, 1);
            chatTargetList.value.unshift(temp);
            flag = true;
            setTimeout(() => {
              chatTargetList.value[0].unReadNum = 0;
            }, 2000);
            break;
          }
        }
        if(!flag){
          // 搜索 urlTarget 的基本信息
          getChatTargetInfo(urlTarget).then((res) => {
            if(res && res.code === 0) {
              chatTargetList.value.unshift(res.data);
              currentChatTargetIndex.value = 0;
            } else {
              message.warn(res.msg);
            }
          });
        }
      } else if(res.data.length > 0) {
        // 当前url不携带聊天对象ID
        currentChatTargetIndex.value = 0;
      }
    } else {
      message.warn(res.msg);
    }
  });
});

onMounted(() => {
  if(props.userSession) {
    userSession.value = props.userSession;
  }
});

onBeforeUnmount(() => {
  Pubsub.unsubscribe(userSessionKey);
});

</script>

<style scoped>

.chat-bubble {
  display: inline-block;
  background-color: #44e337;
  max-width: 700px;
  border-radius: 5px;
  padding: 10px;
  margin: 5px;
  text-align: left;
}

.chat-other-bubble {
  display: inline-block;
  background-color: #ffffff;
  max-width: 700px;
  border-radius: 5px;
  padding: 10px;
  margin: 5px;
  text-align: left;
}

.chat-bubble::after {
  content: '';
  position: absolute;
  bottom: -10px; /* 根据气泡的大小调整 */
  left: 50%;
  transform: translateX(-50%);
  border-width: 10px;
  border-style: solid;
  border-color: transparent transparent #f2f2f2 transparent;
}

</style>